package org.example.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.dao.EmployeeDao;
import org.example.dao.YgDao;
import org.example.service.EmpService;
import org.example.systemset_pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Service
public class EmpServiceImpl extends ServiceImpl<YgDao,Employee> implements EmpService {
    private EmployeeDao employeeDao = new EmployeeDao();

    // 验证员工登录
    public boolean validateLogin(String jobNo, String password) {
        // 1. 检查输入是否为空
        if (jobNo == null || jobNo.trim().isEmpty() || password == null || password.trim().isEmpty()) {
            return false;
        }

        // 2. 查找员工信息
        Employee employee = employeeDao.findByJobNo(jobNo);

        // 3. 检查员工是否存在且状态为active
        if (employee == null || !"active".equals(employee.getStatus())) {
            return false;
        }

        // 4. 验证密码
        String encryptedPassword = encryptPassword(password);
        return encryptedPassword.equals(employee.getPassword());
    }

    // 密码加密方法
    public String encryptPassword(String password) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] hashedBytes = md.digest(password.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : hashedBytes) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return password; // 出错时返回原密码（仅用于示例）
        }
    }

    // 获取员工信息
    public Employee getEmployeeByJobNo(String jobNo) {
        return employeeDao.findByJobNo(jobNo);
    }
}

